"""
Flask数据库操作示例 - 展示ORM模型、仓储模式和服务层
包含CRUD操作、分页查询、事务管理等功能
"""

from flask import Flask, request, jsonify, g
import os
import sys
import time
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey
from sqlalchemy.orm import relationship

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from python_backend_toolkit.database import (
    Base, BaseModel, DatabaseSession, get_db,
    BaseRepository, BaseService
)
from python_backend_toolkit.logging import get_logger
from python_backend_toolkit.utils import generate_uuid
from python_backend_toolkit.api.responses import (
    SuccessResponse, ErrorResponse, PaginatedResponse,
    CreatedResponse, UpdatedResponse, DeletedResponse
)


# ========================================================================
# 数据库模型定义
# ========================================================================

class Category(BaseModel):
    """分类模型"""
    __tablename__ = 'categories'
    
    name = Column(String(100), nullable=False, unique=True)
    description = Column(Text)
    
    # 关系
    articles = relationship("Article", back_populates="category", lazy="dynamic")
    
    def __repr__(self):
        return f"<Category(id={self.id}, name='{self.name}')>"


class Article(BaseModel):
    """文章模型"""
    __tablename__ = 'articles'
    
    title = Column(String(200), nullable=False)
    content = Column(Text, nullable=False)
    summary = Column(String(500))
    author = Column(String(100), nullable=False)
    category_id = Column(Integer, ForeignKey('categories.id'), nullable=False)
    published_at = Column(DateTime)
    view_count = Column(Integer, default=0)
    
    # 关系
    category = relationship("Category", back_populates="articles")
    comments = relationship("Comment", back_populates="article", lazy="dynamic")
    
    def __repr__(self):
        return f"<Article(id={self.id}, title='{self.title}')>"


class Comment(BaseModel):
    """评论模型"""
    __tablename__ = 'comments'
    
    content = Column(Text, nullable=False)
    author = Column(String(100), nullable=False)
    author_email = Column(String(200))
    article_id = Column(Integer, ForeignKey('articles.id'), nullable=False)
    
    # 关系
    article = relationship("Article", back_populates="comments")
    
    def __repr__(self):
        return f"<Comment(id={self.id}, author='{self.author}')>"


# ========================================================================
# 仓储层实现
# ========================================================================

class CategoryRepository(BaseRepository[Category]):
    """分类仓储"""
    
    def find_by_name(self, name: str) -> Optional[Category]:
        """根据名称查找分类"""
        return self.session.query(Category).filter(Category.name == name).first()
    
    def get_with_article_count(self) -> List[Dict[str, Any]]:
        """获取分类及其文章数量"""
        from sqlalchemy import func
        
        result = self.session.query(
            Category,
            func.count(Article.id).label('article_count')
        ).outerjoin(Article).group_by(Category.id).all()
        
        return [
            {
                "category": category,
                "article_count": article_count
            }
            for category, article_count in result
        ]


class ArticleRepository(BaseRepository[Article]):
    """文章仓储"""
    
    def find_by_category(self, category_id: int, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """根据分类查找文章"""
        query = self.session.query(Article).filter(Article.category_id == category_id)
        return self._paginate_query(query, page, size)
    
    def find_published(self, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """查找已发布的文章"""
        query = self.session.query(Article).filter(
            Article.published_at.isnot(None),
            Article.published_at <= datetime.utcnow()
        ).order_by(Article.published_at.desc())
        return self._paginate_query(query, page, size)
    
    def search_by_title(self, keyword: str, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """根据标题搜索文章"""
        query = self.session.query(Article).filter(
            Article.title.contains(keyword)
        ).order_by(Article.created_at.desc())
        return self._paginate_query(query, page, size)
    
    def increment_view_count(self, article_id: int) -> bool:
        """增加文章浏览量"""
        article = self.get_by_id(article_id)
        if article:
            article.view_count += 1
            self.session.commit()
            return True
        return False


class CommentRepository(BaseRepository[Comment]):
    """评论仓储"""
    
    def find_by_article(self, article_id: int, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """根据文章查找评论"""
        query = self.session.query(Comment).filter(
            Comment.article_id == article_id
        ).order_by(Comment.created_at.desc())
        return self._paginate_query(query, page, size)
    
    def find_recent(self, days: int = 7, limit: int = 10) -> List[Comment]:
        """查找最近的评论"""
        since_date = datetime.utcnow() - timedelta(days=days)
        return self.session.query(Comment).filter(
            Comment.created_at >= since_date
        ).order_by(Comment.created_at.desc()).limit(limit).all()


# ========================================================================
# 服务层实现
# ========================================================================

class CategoryService(BaseService[Category]):
    """分类服务"""
    
    def __init__(self, repository: CategoryRepository):
        super().__init__(repository)
        self.repository = repository
    
    def create_category(self, name: str, description: str = None) -> Category:
        """创建分类"""
        # 检查名称是否已存在
        existing = self.repository.find_by_name(name)
        if existing:
            raise ValueError(f"Category with name '{name}' already exists")
        
        category = Category(name=name, description=description)
        return self.repository.create(category)
    
    def get_categories_with_stats(self) -> List[Dict[str, Any]]:
        """获取分类及统计信息"""
        return self.repository.get_with_article_count()


class ArticleService(BaseService[Article]):
    """文章服务"""
    
    def __init__(self, repository: ArticleRepository, category_repository: CategoryRepository):
        super().__init__(repository)
        self.repository = repository
        self.category_repository = category_repository
    
    def create_article(self, title: str, content: str, author: str, 
                      category_id: int, summary: str = None, 
                      publish_now: bool = False) -> Article:
        """创建文章"""
        # 验证分类是否存在
        category = self.category_repository.get_by_id(category_id)
        if not category:
            raise ValueError(f"Category with id {category_id} not found")
        
        article = Article(
            title=title,
            content=content,
            author=author,
            category_id=category_id,
            summary=summary or content[:200] + "..." if len(content) > 200 else content,
            published_at=datetime.utcnow() if publish_now else None
        )
        
        return self.repository.create(article)
    
    def publish_article(self, article_id: int) -> bool:
        """发布文章"""
        article = self.repository.get_by_id(article_id)
        if not article:
            return False
        
        article.published_at = datetime.utcnow()
        self.repository.update(article)
        return True
    
    def get_published_articles(self, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """获取已发布的文章"""
        return self.repository.find_published(page, size)
    
    def search_articles(self, keyword: str, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """搜索文章"""
        return self.repository.search_by_title(keyword, page, size)
    
    def view_article(self, article_id: int) -> Optional[Article]:
        """查看文章（增加浏览量）"""
        article = self.repository.get_by_id(article_id)
        if article:
            self.repository.increment_view_count(article_id)
        return article


class CommentService(BaseService[Comment]):
    """评论服务"""
    
    def __init__(self, repository: CommentRepository, article_repository: ArticleRepository):
        super().__init__(repository)
        self.repository = repository
        self.article_repository = article_repository
    
    def create_comment(self, content: str, author: str, article_id: int, 
                      author_email: str = None) -> Comment:
        """创建评论"""
        # 验证文章是否存在
        article = self.article_repository.get_by_id(article_id)
        if not article:
            raise ValueError(f"Article with id {article_id} not found")
        
        comment = Comment(
            content=content,
            author=author,
            author_email=author_email,
            article_id=article_id
        )
        
        return self.repository.create(comment)
    
    def get_article_comments(self, article_id: int, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """获取文章评论"""
        return self.repository.find_by_article(article_id, page, size)
    
    def get_recent_comments(self, days: int = 7, limit: int = 10) -> List[Comment]:
        """获取最近评论"""
        return self.repository.find_recent(days, limit)


def create_database_app() -> Flask:
    """创建数据库示例Flask应用"""
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'database-demo-secret'
    
    # 初始化数据库
    db_session = DatabaseSession(
        database_url="sqlite:///flask_database_demo.db",
        echo=True  # 显示SQL语句
    )
    
    # 创建表
    db_session.create_tables()
    
    logger = get_logger("DatabaseApp")
    
    # 初始化仓储和服务
    def get_repositories_and_services():
        """获取仓储和服务实例"""
        session = db_session.get_session()
        
        # 仓储
        category_repo = CategoryRepository(Category, session)
        article_repo = ArticleRepository(Article, session)
        comment_repo = CommentRepository(Comment, session)
        
        # 服务
        category_service = CategoryService(category_repo)
        article_service = ArticleService(article_repo, category_repo)
        comment_service = CommentService(comment_repo, article_repo)
        
        return {
            'category_service': category_service,
            'article_service': article_service,
            'comment_service': comment_service,
            'session': session
        }
    
    @app.before_request
    def before_request():
        """请求前处理"""
        g.request_id = generate_uuid()
        g.start_time = time.time()
        g.services = get_repositories_and_services()
    
    @app.after_request
    def after_request(response):
        """请求后处理"""
        duration = time.time() - g.start_time
        logger.info(
            "Request completed",
            request_id=g.request_id,
            method=request.method,
            path=request.path,
            status_code=response.status_code,
            duration=duration
        )
        
        # 关闭数据库会话
        if hasattr(g, 'services') and 'session' in g.services:
            g.services['session'].close()
        
        return response
    
    # ========================================================================
    # 分类管理API
    # ========================================================================
    
    @app.route('/categories', methods=['GET'])
    def list_categories():
        """获取分类列表"""
        try:
            include_stats = request.args.get('include_stats', 'false').lower() == 'true'
            
            if include_stats:
                categories_data = g.services['category_service'].get_categories_with_stats()
                categories = []
                for item in categories_data:
                    category_dict = item['category'].to_dict()
                    category_dict['article_count'] = item['article_count']
                    categories.append(category_dict)
            else:
                categories = [cat.to_dict() for cat in g.services['category_service'].get_all()]
            
            response = SuccessResponse.create(
                data={"categories": categories},
                message="Categories retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve categories: {str(e)}"
            ).dict()), 500
    
    @app.route('/categories', methods=['POST'])
    def create_category():
        """创建分类"""
        try:
            data = request.get_json()
            name = data.get('name', '').strip()
            description = data.get('description', '').strip()
            
            if not name:
                return jsonify(ErrorResponse.create(
                    message="Category name is required"
                ).dict()), 400
            
            category = g.services['category_service'].create_category(name, description)
            
            response = CreatedResponse.create(
                data={"category": category.to_dict()},
                message="Category created successfully"
            )
            return jsonify(response.dict()), 201
            
        except ValueError as e:
            return jsonify(ErrorResponse.create(
                message=str(e)
            ).dict()), 409
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to create category: {str(e)}"
            ).dict()), 500
    
    @app.route('/categories/<int:category_id>', methods=['GET'])
    def get_category(category_id: int):
        """获取分类详情"""
        try:
            category = g.services['category_service'].get_by_id(category_id)
            
            if not category:
                return jsonify(ErrorResponse.create(
                    message="Category not found"
                ).dict()), 404
            
            response = SuccessResponse.create(
                data={"category": category.to_dict()},
                message="Category retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve category: {str(e)}"
            ).dict()), 500
    
    @app.route('/categories/<int:category_id>', methods=['PUT'])
    def update_category(category_id: int):
        """更新分类"""
        try:
            data = request.get_json()
            
            category = g.services['category_service'].get_by_id(category_id)
            if not category:
                return jsonify(ErrorResponse.create(
                    message="Category not found"
                ).dict()), 404
            
            # 更新字段
            if 'name' in data:
                category.name = data['name'].strip()
            if 'description' in data:
                category.description = data['description'].strip()
            
            updated_category = g.services['category_service'].update(category)
            
            response = UpdatedResponse.create(
                data={"category": updated_category.to_dict()},
                message="Category updated successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to update category: {str(e)}"
            ).dict()), 500
    
    @app.route('/categories/<int:category_id>', methods=['DELETE'])
    def delete_category(category_id: int):
        """删除分类"""
        try:
            success = g.services['category_service'].delete(category_id)
            
            if not success:
                return jsonify(ErrorResponse.create(
                    message="Category not found"
                ).dict()), 404
            
            response = DeletedResponse.create(
                message="Category deleted successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to delete category: {str(e)}"
            ).dict()), 500
    
    # ========================================================================
    # 文章管理API
    # ========================================================================
    
    @app.route('/articles', methods=['GET'])
    def list_articles():
        """获取文章列表"""
        try:
            page = int(request.args.get('page', 1))
            size = min(int(request.args.get('size', 10)), 50)
            category_id = request.args.get('category_id')
            published_only = request.args.get('published_only', 'false').lower() == 'true'
            search = request.args.get('search', '').strip()
            
            if search:
                # 搜索文章
                result = g.services['article_service'].search_articles(search, page, size)
            elif published_only:
                # 只获取已发布的文章
                result = g.services['article_service'].get_published_articles(page, size)
            elif category_id:
                # 根据分类获取文章
                result = g.services['article_service'].repository.find_by_category(
                    int(category_id), page, size
                )
            else:
                # 获取所有文章
                result = g.services['article_service'].get_paginated(page, size)
            
            # 转换为字典格式
            articles = [article.to_dict() for article in result['items']]
            
            response = PaginatedResponse.create(
                data=articles,
                page=result['page'],
                size=result['size'],
                total=result['total'],
                pages=result['pages'],
                message="Articles retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve articles: {str(e)}"
            ).dict()), 500
    
    @app.route('/articles', methods=['POST'])
    def create_article():
        """创建文章"""
        try:
            data = request.get_json()
            title = data.get('title', '').strip()
            content = data.get('content', '').strip()
            author = data.get('author', '').strip()
            category_id = data.get('category_id')
            summary = data.get('summary', '').strip()
            publish_now = data.get('publish_now', False)
            
            if not all([title, content, author, category_id]):
                return jsonify(ErrorResponse.create(
                    message="Title, content, author, and category_id are required"
                ).dict()), 400
            
            article = g.services['article_service'].create_article(
                title=title,
                content=content,
                author=author,
                category_id=category_id,
                summary=summary or None,
                publish_now=publish_now
            )
            
            response = CreatedResponse.create(
                data={"article": article.to_dict()},
                message="Article created successfully"
            )
            return jsonify(response.dict()), 201
            
        except ValueError as e:
            return jsonify(ErrorResponse.create(
                message=str(e)
            ).dict()), 400
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to create article: {str(e)}"
            ).dict()), 500
    
    @app.route('/articles/<int:article_id>', methods=['GET'])
    def get_article(article_id: int):
        """获取文章详情"""
        try:
            increment_view = request.args.get('increment_view', 'true').lower() == 'true'
            
            if increment_view:
                article = g.services['article_service'].view_article(article_id)
            else:
                article = g.services['article_service'].get_by_id(article_id)
            
            if not article:
                return jsonify(ErrorResponse.create(
                    message="Article not found"
                ).dict()), 404
            
            response = SuccessResponse.create(
                data={"article": article.to_dict()},
                message="Article retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve article: {str(e)}"
            ).dict()), 500
    
    @app.route('/articles/<int:article_id>/publish', methods=['POST'])
    def publish_article(article_id: int):
        """发布文章"""
        try:
            success = g.services['article_service'].publish_article(article_id)
            
            if not success:
                return jsonify(ErrorResponse.create(
                    message="Article not found"
                ).dict()), 404
            
            response = SuccessResponse.create(
                message="Article published successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to publish article: {str(e)}"
            ).dict()), 500
    
    # ========================================================================
    # 评论管理API
    # ========================================================================
    
    @app.route('/articles/<int:article_id>/comments', methods=['GET'])
    def get_article_comments(article_id: int):
        """获取文章评论"""
        try:
            page = int(request.args.get('page', 1))
            size = min(int(request.args.get('size', 10)), 50)
            
            result = g.services['comment_service'].get_article_comments(article_id, page, size)
            
            # 转换为字典格式
            comments = [comment.to_dict() for comment in result['items']]
            
            response = PaginatedResponse.create(
                data=comments,
                page=result['page'],
                size=result['size'],
                total=result['total'],
                pages=result['pages'],
                message="Comments retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve comments: {str(e)}"
            ).dict()), 500
    
    @app.route('/articles/<int:article_id>/comments', methods=['POST'])
    def create_comment(article_id: int):
        """创建评论"""
        try:
            data = request.get_json()
            content = data.get('content', '').strip()
            author = data.get('author', '').strip()
            author_email = data.get('author_email', '').strip()
            
            if not all([content, author]):
                return jsonify(ErrorResponse.create(
                    message="Content and author are required"
                ).dict()), 400
            
            comment = g.services['comment_service'].create_comment(
                content=content,
                author=author,
                article_id=article_id,
                author_email=author_email or None
            )
            
            response = CreatedResponse.create(
                data={"comment": comment.to_dict()},
                message="Comment created successfully"
            )
            return jsonify(response.dict()), 201
            
        except ValueError as e:
            return jsonify(ErrorResponse.create(
                message=str(e)
            ).dict()), 400
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to create comment: {str(e)}"
            ).dict()), 500
    
    @app.route('/comments/recent', methods=['GET'])
    def get_recent_comments():
        """获取最近评论"""
        try:
            days = int(request.args.get('days', 7))
            limit = min(int(request.args.get('limit', 10)), 50)
            
            comments = g.services['comment_service'].get_recent_comments(days, limit)
            
            response = SuccessResponse.create(
                data={
                    "comments": [comment.to_dict() for comment in comments],
                    "days": days,
                    "limit": limit
                },
                message="Recent comments retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve recent comments: {str(e)}"
            ).dict()), 500
    
    # ========================================================================
    # 数据库管理API
    # ========================================================================
    
    @app.route('/database/init-data', methods=['POST'])
    def init_sample_data():
        """初始化示例数据"""
        try:
            # 创建示例分类
            categories = [
                {"name": "技术", "description": "技术相关文章"},
                {"name": "生活", "description": "生活感悟和经验分享"},
                {"name": "学习", "description": "学习心得和方法"}
            ]
            
            created_categories = []
            for cat_data in categories:
                try:
                    category = g.services['category_service'].create_category(
                        cat_data['name'], cat_data['description']
                    )
                    created_categories.append(category)
                except ValueError:
                    # 分类已存在，跳过
                    pass
            
            # 如果没有创建新分类，获取现有分类
            if not created_categories:
                created_categories = g.services['category_service'].get_all()[:3]
            
            # 创建示例文章
            articles_data = [
                {
                    "title": "Python后端开发最佳实践",
                    "content": "本文介绍了Python后端开发的最佳实践，包括代码结构、设计模式、性能优化等方面的内容。",
                    "author": "张三",
                    "category_id": created_categories[0].id if created_categories else 1,
                    "publish_now": True
                },
                {
                    "title": "Flask框架深入解析",
                    "content": "Flask是一个轻量级的Python Web框架，本文深入分析了Flask的核心概念和高级用法。",
                    "author": "李四",
                    "category_id": created_categories[0].id if created_categories else 1,
                    "publish_now": True
                },
                {
                    "title": "工作生活平衡的艺术",
                    "content": "如何在繁忙的工作中保持生活的平衡，这是每个职场人都需要思考的问题。",
                    "author": "王五",
                    "category_id": created_categories[1].id if len(created_categories) > 1 else 1,
                    "publish_now": False
                }
            ]
            
            created_articles = []
            for article_data in articles_data:
                article = g.services['article_service'].create_article(**article_data)
                created_articles.append(article)
            
            # 创建示例评论
            if created_articles:
                comments_data = [
                    {
                        "content": "很好的文章，学到了很多！",
                        "author": "读者A",
                        "article_id": created_articles[0].id,
                        "author_email": "reader_a@example.com"
                    },
                    {
                        "content": "期待更多这样的技术分享。",
                        "author": "读者B",
                        "article_id": created_articles[0].id
                    },
                    {
                        "content": "Flask确实是个很棒的框架。",
                        "author": "读者C",
                        "article_id": created_articles[1].id
                    }
                ]
                
                for comment_data in comments_data:
                    g.services['comment_service'].create_comment(**comment_data)
            
            response = SuccessResponse.create(
                data={
                    "categories_created": len(created_categories),
                    "articles_created": len(created_articles),
                    "comments_created": 3
                },
                message="Sample data initialized successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to initialize sample data: {str(e)}"
            ).dict()), 500
    
    @app.route('/database/stats', methods=['GET'])
    def get_database_stats():
        """获取数据库统计信息"""
        try:
            categories_count = len(g.services['category_service'].get_all())
            articles_count = len(g.services['article_service'].get_all())
            comments_count = len(g.services['comment_service'].get_all())
            
            # 获取已发布文章数量
            published_articles = g.services['article_service'].get_published_articles(1, 1000)
            published_count = published_articles['total']
            
            response = SuccessResponse.create(
                data={
                    "categories": categories_count,
                    "articles": {
                        "total": articles_count,
                        "published": published_count,
                        "draft": articles_count - published_count
                    },
                    "comments": comments_count
                },
                message="Database statistics retrieved successfully"
            )
            return jsonify(response.dict())
            
        except Exception as e:
            return jsonify(ErrorResponse.create(
                message=f"Failed to retrieve database statistics: {str(e)}"
            ).dict()), 500
    
    # ========================================================================
    # 应用信息
    # ========================================================================
    
    @app.route('/health', methods=['GET'])
    def health_check():
        """健康检查"""
        try:
            # 检查数据库连接
            db_session.check_connection()
            return jsonify({
                "status": "healthy",
                "database": "connected",
                "timestamp": datetime.utcnow().isoformat()
            })
        except Exception as e:
            return jsonify({
                "status": "unhealthy",
                "database": "disconnected",
                "error": str(e),
                "timestamp": datetime.utcnow().isoformat()
            }), 500
    
    @app.route('/info', methods=['GET'])
    def app_info():
        """应用信息"""
        return jsonify({
            "name": "Flask Database Example",
            "version": "1.0.0",
            "description": "Flask数据库操作示例应用",
            "database": "SQLite",
            "endpoints": {
                "categories": [
                    "GET    /categories",
                    "POST   /categories",
                    "GET    /categories/<id>",
                    "PUT    /categories/<id>",
                    "DELETE /categories/<id>"
                ],
                "articles": [
                    "GET  /articles",
                    "POST /articles",
                    "GET  /articles/<id>",
                    "POST /articles/<id>/publish"
                ],
                "comments": [
                    "GET  /articles/<id>/comments",
                    "POST /articles/<id>/comments",
                    "GET  /comments/recent"
                ],
                "management": [
                    "POST /database/init-data",
                    "GET  /database/stats"
                ]
            },
            "features": [
                "ORM模型定义",
                "仓储模式实现",
                "服务层封装",
                "分页查询",
                "关联查询",
                "事务管理"
            ]
        })
    
    return app


if __name__ == '__main__':
    app = create_database_app()
    
    print("=" * 60)
    print("Flask Database Example")
    print("=" * 60)
    print("数据库操作功能演示:")
    print("  分类管理:")
    print("    GET    /categories - 获取分类列表")
    print("    POST   /categories - 创建分类")
    print("    GET    /categories/<id> - 获取分类详情")
    print("    PUT    /categories/<id> - 更新分类")
    print("    DELETE /categories/<id> - 删除分类")
    print()
    print("  文章管理:")
    print("    GET  /articles - 获取文章列表")
    print("    POST /articles - 创建文章")
    print("    GET  /articles/<id> - 获取文章详情")
    print("    POST /articles/<id>/publish - 发布文章")
    print()
    print("  评论管理:")
    print("    GET  /articles/<id>/comments - 获取文章评论")
    print("    POST /articles/<id>/comments - 创建评论")
    print("    GET  /comments/recent - 获取最近评论")
    print()
    print("  数据库管理:")
    print("    POST /database/init-data - 初始化示例数据")
    print("    GET  /database/stats - 获取数据库统计")
    print()
    print("  特性:")
    print("    - ORM模型定义和关联")
    print("    - 仓储模式实现")
    print("    - 服务层封装")
    print("    - 分页查询支持")
    print("    - 事务管理")
    print("=" * 60)
    
    app.run(
        host='0.0.0.0',
        port=5004,
        debug=True
    )